#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <ctype.h>
#include <signal.h>
#include <sys/wait.h>
#include "wrap.h"
#define SERVER_PORT 6666
void recyle(int num)
{
        pid_t pid;
        while ((pid = waitpid(-1, NULL, WNOHANG)) > 0)
        {
                printf("child died , pid = %d\n",pid);
        }
}
int main(int argc, char const *argv[])
{
        int lfd,cfd;
        struct sockaddr_in server_addr;
        struct sockaddr_in client_addr;
        socklen_t client_addr_len;
        char buf[BUFSIZ];
        int len;
        int i = 0;
        
        client_addr_len = sizeof(client_addr);

        lfd = Socket(AF_INET,SOCK_STREAM,0);
        bzero(&server_addr,sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        server_addr.sin_port = htons(SERVER_PORT);
        server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
        Bind(lfd,(struct sockaddr *)&server_addr,sizeof(server_addr));

        Listen(lfd,128);
        printf("Start accept ......\n");
        //使用信号回收子进程pcb
        struct sigaction act;
        act.sa_handler = recyle;
        act.sa_flags = 0;
        sigemptyset(&act.sa_mask);
        sigaction(SIGCHLD,&act,NULL);
        while (1)
        {
                cfd = Accept(lfd,(struct sockaddr *)&client_addr,&client_addr_len);
                printAddr("client connect", &client_addr);
                if(cfd == -1){
                        perr_exit("accept error");
                }
                //创建子进程
                pid_t pid = fork();
                if(pid == 0){
                        Close(lfd);
                        //child process
                        //通讯的过程
                        while (1){
                                len = Read(cfd,buf,sizeof(buf));
                                if(len == -1){
                                        perr_exit("read error");
                                }else if(len == 0){
                                        printf("客户端断开了连接\n");
                                        Close(cfd);
                                        break;
                                }else{
                                        printf("recv buf: %s\n",buf);
                                        for ( i = 0; i < len; i++){
                                                buf[i] = toupper(buf[i]);
                                        }
                                        Write(cfd,buf,len);
                                }
                        }
                        //干掉子进程
                        return 0;
                }else if(pid > 0){ 
                        Close(cfd);
                }
        }
        Close(lfd);
        return 0;
}


